/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package acousticfield3d.gui;

import acousticfield3d.math.M;
import acousticfield3d.math.Quaternion;
import acousticfield3d.math.Vector3f;
import acousticfield3d.simulation.Transducer;
import acousticfield3d.utils.Parse;
import java.util.ArrayList;

/**
 *
 * @author am14010
 */
public class ImportTransducersFromObjForm extends javax.swing.JFrame {

    private final MainForm mf;
    
    public ImportTransducersFromObjForm(MainForm mf) {
        this.mf = mf;
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        objArea = new javax.swing.JTextArea();
        importObjButton = new javax.swing.JButton();
        scaleObjText = new javax.swing.JTextField();
        centerObjCheck = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Import Array from Obj");

        objArea.setColumns(20);
        objArea.setRows(5);
        jScrollPane1.setViewportView(objArea);

        importObjButton.setText("Import from Obj");
        importObjButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                importObjButtonActionPerformed(evt);
            }
        });

        scaleObjText.setText("0.0253936008");

        centerObjCheck.setText("center");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(importObjButton)
                        .addGap(18, 18, 18)
                        .addComponent(scaleObjText, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(centerObjCheck)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(importObjButton)
                    .addComponent(centerObjCheck)
                    .addComponent(scaleObjText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void importObjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importObjButtonActionPerformed
        final boolean center = centerObjCheck.isSelected();
        final String[] lines = objArea.getText().split("\\n");
        final float scale = Parse.toFloat( scaleObjText.getText() );

        final ArrayList<Vector3f> positions = new ArrayList<>();
        final ArrayList<ArrayList<Integer>> faces = new ArrayList<>();

        final boolean wasEmpty = mf.simulation.getTransducers().isEmpty();
        
        int vIndex = 0;
        Vector3f total = new Vector3f();
        for (String l : lines) {
            if(l.startsWith("v")){
                String[] coords = l.split(" ");
                Vector3f v = new Vector3f(coords[2], coords[3], coords[4]);

                v.multLocal(scale);

                total.addLocal(v);
                positions.add( v );
                vIndex++;
            }
            if(l.startsWith("f")){
                String[] inds = l.split(" ");
                final int length = inds.length;
                ArrayList<Integer> face = new ArrayList<>();
                for(int i = 1; i < length; ++i){
                    face.add( Integer.parseInt( inds[i] ) );
                }
                faces.add( face );
            }
        }
        total.divideLocal( vIndex );
        if(center){
            for(Vector3f v : positions){
                v.subtractLocal( total );
            }
        }

        ArrayList<Vector3f> faceV = new ArrayList<>();
        for( ArrayList<Integer> face : faces){
            faceV.clear();
            for(Integer i : face){
                faceV.add( positions.get(i - 1) ); //obj starts numbering from 1
            }
            Vector3f pos = Vector3f.calcAverage( faceV );
            Vector3f normal = Vector3f.calcNormal( faceV );

            Transducer t = mf.addTransducersForm.createTransducer();

            t.getTransform().setTranslation( pos );
            Quaternion q = new Quaternion();
            q.lookAt(normal, Vector3f.UNIT_Y);
            q.rotateLocalSpace(M.degToRad( 90 ), 0, 0);
            t.getTransform().getRotation().set(q);

            mf.addTransducersForm.addTransducer(t);
        }
        
        if(wasEmpty){
            mf.updateBoundaries();
            mf.adjustGUIGainAndCameras();
        }
        mf.needUpdate();
    }//GEN-LAST:event_importObjButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox centerObjCheck;
    private javax.swing.JButton importObjButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea objArea;
    private javax.swing.JTextField scaleObjText;
    // End of variables declaration//GEN-END:variables
}
